<!-- FollowList.vue -->
<template>
  <div class="follow-container">
    <el-tabs v-model="activeTab" class="custom-tabs" @tab-change="handleTabChange">
      <el-tab-pane label="我的关注" name="following">
        <div v-if="followingList.length > 0" class="user-grid">
          <div v-for="user in followingList" :key="user.id" class="user-card" >
            <div class="card-header">
              <el-avatar :size="60" :src="user.avatar || defaultAvatar"  @click.stop="goToProfile(user.id)"/>
              <div class="user-meta">
                <h3 class="username">{{ user.userName }}</h3>
              </div>
            </div>
            <p class="bio">{{ user.bio || '这个用户很懒，什么都没留下~' }}</p>
            <div class="stats">
              <div class="stat-item">
                <span class="stat-number">{{ user.fansCount || 0 }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ user.followCount || 0 }}</span>
                <span class="stat-label">关注</span>
              </div>
            </div>
            <el-button 
              class="action-btn" 
              size="small" 
              type="danger" 
              plain 
              round
              @click="unfollow(user.followId)"
            >
              <el-icon><Close /></el-icon> 取消关注
            </el-button>
          </div>
        </div>
        <el-empty v-else description="你还没有关注任何人哦~" image="/src/assets/no-data.svg">
          <el-button type="primary" size="small">去发现用户</el-button>
        </el-empty>
      </el-tab-pane>

      <el-tab-pane label="我的粉丝" name="followers">
        <div v-if="followersList.length > 0" class="user-grid">
          <div v-for="user in followersList" :key="user.id" class="user-card"  >
            <div class="card-header">
              <el-avatar :size="60" :src="user.avatar || defaultAvatar"  @click.stop="goToProfile(user.id)"/>
              <div class="user-meta">
                <h3 class="username">{{ user.userName }}</h3>
              </div>
            </div>
            <p class="bio">{{ user.bio || '这个用户很懒，什么都没留下~' }}</p>
            <div class="stats">
              <div class="stat-item">
                <span class="stat-number">{{ user.fansCount || 0 }}</span>
                <span class="stat-label">粉丝</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ user.followCount || 0 }}</span>
                <span class="stat-label">关注</span>
              </div>
            </div>
            <el-button 
              class="action-btn" 
              size="small" 
              :type="user.isFollowing ? 'info' : 'primary'" 
              plain 
              round
              @click="toggleFollow(user)"
            >
              <el-icon v-if="user.isFollowing"><Check /></el-icon>
              <el-icon v-else><Plus /></el-icon>
              {{ user.isFollowing ? '已关注' : '关注' }}
            </el-button>
          </div>
        </div>
        <el-empty v-else description="还没有粉丝，快去活跃一下吧~" image="/src/assets/no-data.svg">
          <el-button type="primary" size="small">去发布内容</el-button>
        </el-empty>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Check, Plus, Close } from '@element-plus/icons-vue'
import axios from 'axios'
import img from '/src/assets/images/doro.jpg'
import router from '@/router'
// import { useRouter } from 'vue-router'

// const router = useRouter()
const props = defineProps({
  id: {
    type: Number,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  }
})

const activeTab = ref('following')
const followingList = ref([])
const followersList = ref([])
const defaultAvatar = img
// 添加跳转方法
const goToProfile = (userId) => {
  router.push(`/userfile/${userId}`)
}
// 获取关注列表
const fetchFollowingList = async () => {
  try {
    const response = await axios.get(`/api/auth/getFollowees/${props.id}`)
    if (response.data.code === 200) {
      followingList.value = response.data.data.map(user => ({
        ...user,
        avatar: user.avatar || defaultAvatar,
        isFollowing: true // 关注列表中的用户都是已关注的
      }))
    } else {
      ElMessage.error(response.data.message || '获取关注列表失败')
    }
  } catch (error) {
    ElMessage.error('获取关注列表失败')
    console.error('Error fetching following list:', error)
  }
}

// 获取粉丝列表
const fetchFollowersList = async () => {
  try {
    const response = await axios.get(`/api/auth/getFollower/${props.id}`)
    if (response.data.code === 200) {
      followersList.value = response.data.data.map(user => ({
        ...user,
        avatar: user.avatar || defaultAvatar,
        isFollowing: false // 初始状态，需要后续检查是否已关注
      }))
      
      // 检查粉丝列表中哪些用户已经被当前用户关注
      checkFollowStatus()
    } else {
      ElMessage.error(response.data.message || '获取粉丝列表失败')
    }
  } catch (error) {
    ElMessage.error('获取粉丝列表失败')
    console.error('Error fetching followers list:', error)
  }
}

// 检查粉丝列表中哪些用户已经被当前用户关注
const checkFollowStatus = async () => {
  try {
    // 获取当前用户的关注列表
    const response = await axios.get(`/api/auth/getFollowees/${props.id}`)
    if (response.data.code === 200) {
      const followingIds = response.data.data.map(user => user.id)
      followersList.value = followersList.value.map(user => ({
        ...user,
        isFollowing: followingIds.includes(user.id)
      }))
    }
  } catch (error) {
    console.error('Error checking follow status:', error)
  }
}

const unfollow = async (followId) => {
  try {
    const response = await axios.post(`/api/auth/delFollowee/${followId}`)
    if (response.data.code === 200) {
      followingList.value = followingList.value.filter(user => user.followId !== followId)
      ElMessage.success(response.data.data || '已取消关注')
    } else {
      ElMessage.error(response.data.message || '取消关注失败')
    }
  } catch (error) {
    ElMessage.error('取消关注失败')
    console.error('Error unfollowing user:', error)
  }
}

const toggleFollow = async (user) => {
  try {
    if (user.isFollowing) {
      // 取消关注 - 需要先找到对应的followId
      const followUser = followingList.value.find(u => u.id === user.id)
      if (followUser) {
        await unfollow(followUser.followId)
        user.isFollowing = false
      } else {
        ElMessage.error('找不到关注记录')
      }
    } else {
      // 关注
      const response = await axios.post('/api/auth/addFollowee', {
        followerId: props.id,
        followeeId: user.id,
        followTime: new Date().toISOString().replace('T', ' ').substring(0, 19)
      })
      
      if (response.data.code === 200) {
        user.isFollowing = true
        ElMessage.success(response.data.data || '关注成功')
        // 刷新关注列表
        fetchFollowingList()
      } else {
        ElMessage.error(response.data.message || '关注失败')
      }
    }
  } catch (error) {
    ElMessage.error('操作失败')
    console.error('Error toggling follow:', error)
  }
}

// 切换标签时加载对应数据
const handleTabChange = (tab) => {
  if (tab === 'following') {
    fetchFollowingList()
  } else {
    fetchFollowersList()
  }
}

// 初始化加载数据
onMounted(() => {
  fetchFollowingList()
})
</script>

<style scoped>
/* 保持原有的样式不变 */
.follow-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.custom-tabs {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.custom-tabs :deep(.el-tabs__header) {
  margin-bottom: 24px;
}

.custom-tabs :deep(.el-tabs__nav-wrap::after) {
  height: 1px;
  background-color: #f0f2f5;
}

.custom-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  font-weight: 500;
  padding: 0 24px;
}

.user-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.user-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  border: 1px solid #f0f2f5;
}

.user-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.user-meta {
  margin-left: 16px;
}

.username {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
}

.bio {
  color: #666;
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 16px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stats {
  display: flex;
  justify-content: space-around;
  margin: 20px 0;
  padding: 12px 0;
  border-top: 1px solid #f0f2f5;
  border-bottom: 1px solid #f0f2f5;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 18px;
  font-weight: 600;
  color: #1d2129;
}

.stat-label {
  font-size: 12px;
  color: #8a919f;
  margin-top: 4px;
}

.action-btn {
  width: 100%;
  margin-top: 12px;
}

.action-btn i {
  margin-right: 6px;
}

.el-tag {
  margin-left: 8px;
  height: 22px;
  line-height: 20px;
}

.el-empty {
  padding: 40px 0;
}

.el-empty__image {
  width: 200px;
}
.user-card {
  cursor: pointer;
  transition: transform 0.2s;
}

.user-card:hover {
  transform: translateY(-3px);
}

/* 确保按钮点击不会触发卡片跳转 */
.action-btn {
  pointer-events: auto;
}
</style>